package day0727API;

public class Test2 {
    public static void main(String[] args) {
        Bank2  bank=new Bank2();
        Thread t1=new Thread(){
            public void run() {
                while(true){
                    bank.getMoney();//取款
                    int rs=bank.checkUserMoney();//查询余额
                    System.out.println(rs);
                    Thread.yield();//让t1进入Runnable状态，让t2运行
                }
            }
        };
        t1.start();

        Thread t2=new Thread(()-> {
            while(true){
                bank.getMoney();//取款
                int rs=bank.checkUserMoney();//查询余额
                System.out.println(rs);
                Thread.yield();//让t1进入Runnable状态，让t2运行
            }
        });
        t2.start();
    }

}

class Bank2{
    int userMoney=10;
    //synchronized: 确保某线程执行此方法时，其他线程不能此方法
    public synchronized int  getMoney(){//取钱
        userMoney--;
        if(userMoney==0){
            throw new RuntimeException("不能再取钱了");
        }
        return 1;
    }
    public int checkUserMoney(){//查询余额
        return userMoney;
    }
}

